# img/tools.py
from PIL import Image

def resize_image_to_fit_screen(image_path, output_path, screen_width=320, screen_height=240):
    """
    将图片等比例压缩以适应屏幕尺寸，并保存到指定路径。
    :param image_path: 原始图片的路径
    :param output_path: 压缩后图片的保存路径
    :param screen_width: 屏幕宽度
    :param screen_height: 屏幕高度
    """
    # 打开原始图片
    image = Image.open(image_path)
    
    # 获取原始图片的尺寸
    image_width, image_height = image.size
    
    # 计算缩放比例
    scale_width = screen_width / image_width
    scale_height = screen_height / image_height
    scale = min(scale_width, scale_height)  # 选择较小的缩放比例以确保图片完全显示
    
    # 根据缩放比例调整图片大小
    new_width = int(image_width * scale)
    new_height = int(image_height * scale)
    resized_image = image.resize((new_width, new_height), Image.ANTIALIAS)
    
    # 保存压缩后的图片
    resized_image.save(output_path)